package tasks;

import jade.core.Agent;
import jade.core.behaviours.DataStore;

import jade.domain.FIPAAgentManagement.FailureException;
import jade.domain.FIPAAgentManagement.NotUnderstoodException;

import jade.domain.FIPAAgentManagement.RefuseException;

import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import jade.lang.acl.UnreadableException;

import jade.proto.ContractNetResponder;

import java.io.IOException;

import java.util.ArrayList;

public class ContractNetRB extends ContractNetResponder {
    public ContractNetRB(Agent agent, MessageTemplate messageTemplate,
                         DataStore dataStore) {
        super(agent, messageTemplate, dataStore);
    }

    public ContractNetRB(Agent agent, MessageTemplate messageTemplate) {
        super(agent, messageTemplate);
    }
    
    @Override
    protected ACLMessage handleCfp(ACLMessage cfp) throws 
        NotUnderstoodException, RefuseException {
        ACLMessage propose = cfp.createReply();
        propose.setPerformative(ACLMessage.PROPOSE);
          try {
              propose.setContentObject(((ContractorAgent)myAgent).
            generateProposal((ArrayList<Long>)cfp.getContentObject()));
          } catch (IOException e) {
              throw new RefuseException("Unable to read content object");
          } catch (UnreadableException e) {
              throw new NotUnderstoodException("Unable to read content object");
          }
          return propose;
    }
    
    @Override
    protected ACLMessage handleAcceptProposal(ACLMessage cfp, 
        ACLMessage propose, ACLMessage accept) throws FailureException {
        ACLMessage inform = accept.createReply();
        String[] offers = accept.getContent().split(
            ConfigurationManager.SEPARATOR);
        ((ContractorAgent)myAgent).printOffers(offers);
        inform.setPerformative(ACLMessage.INFORM);
        return inform;
    }
}
